package org.upfrost;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import junit.framework.Assert;

import org.junit.Test;
import org.upfrost.mapping.ClassProxy;
import org.upfrost.mapping.classes.TestClass2;


public class AtomicExecutionGroupTest extends BaseTestClass
{

	@Test
	public void testSimpleAtomic()
	{
		TestClass2 tc21 = new TestClass2();
		tc21.setStrValue("value1");
		tc21.setSomeDate(new Date());
		m_dao2.insert(tc21);

		String value = m_mapper.execute(new AtomicExecutionGroup<String>() {
			@Override
			public String execute(MapperSession session) throws SQLException {
				TestClass2 tc1 = session.createQuery("select * from test2 limit 1").asClass(TestClass2.class).single();
				return tc1.getStrValue();
			}
		});

		Assert.assertEquals("value1", value);
	}

	@Test
	public void testAtomicCommit()
	{
		Integer id = m_mapper.execute(new AtomicExecutionGroup<Integer>() {
			@Override
			public Integer execute(MapperSession session) throws SQLException {
				session.createQuery("insert into test2 (\"value\",\"when\") VALUES (?,?)").param("some text", new Date()).update();

				TestClass2 tc1 = session.createQuery("select * from test2 limit 1").asClass(TestClass2.class).single();
				return tc1.getId();
			}
		});

		Assert.assertEquals(new Integer(1), id);

		createNewSession();

		TestClass2 tc = m_dao2.get(id);
		Assert.assertEquals("some text", tc.getStrValue());
	}

	@Test
	public void testAtomicRollback()
	{
		try {
			m_mapper.execute(new AtomicExecutionGroup<Integer>() {
				@Override
				public Integer execute(MapperSession session) throws SQLException {
					session.createQuery("insert into test2 (\"value\",\"when\") VALUES (?,?)").param("some text", new Date()).update();
					session.createQuery("insert into test2 (\"value\",\"when\") VALUES (?,?)").param("some other text", null).update();
					session.createQuery("insert into test2 (\"value\",\"when\") VALUES (?,?)").param("dummy text", new Date()).update();

					List<TestClass2> lst = session.createQuery("select * from test2").asClass(TestClass2.class).list();

					Assert.assertEquals(3, lst.size());

					throw new RuntimeException("test rollback");
				}
			});
		} catch (Exception exc)
		{
			// ignore
		}

		
		createNewSession();

		// As an exception was raised in the AtomicExecutionGroup call, all the changes should have been rolled back.
		List<TestClass2> lst = m_session.createQuery("select * from test2").asClass(TestClass2.class).list();
		Assert.assertEquals(0, lst.size());
	}


}
